package com.teamwechat.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.teamwechat.db.pojo.MessageEntity;
import com.teamwechat.exception.TeamsException;
import com.teamwechat.mapper.TbDeptMapper;
import com.teamwechat.mapper.TbUserMapper;
import com.teamwechat.pojo.Contacts;
import com.teamwechat.pojo.TbUser;
import com.teamwechat.pojo.vo.TbUserVo;
import com.teamwechat.service.UserService;
import com.teamwechat.task.MessageTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.util.*;

@Slf4j
@Service
@Scope("prototype")
public class UserServiceImpl implements UserService {
    @Value("${wx.app-id}")
    private String appId;

    @Value("${wx.app-secret}")
    private String appSecret;

    @Autowired
    private TbUserMapper tbUserMapper;

    @Autowired
    private MessageTask messageTask;

    private String getOpenId(String code){
        String url="https://api.weixin.qq.com/sns/jscode2session";
        HashMap map=new HashMap();
        map.put("appid", appId);
        map.put("secret", appSecret);
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String response= HttpUtil.post(url,map);
        JSONObject json= JSONUtil.parseObj(response);
        String openId=json.getStr("openid");
        if(openId==null||openId.length()==0){
            throw new RuntimeException("临时登陆凭证错误");
        }
        return openId;
    }

    @Override
    public int registerUser(String registerCode, String code, String nickname, String photo) {
//        if(registerCode.equals("000000")){
//            boolean bool=tbUserMapper.haveRootUser();
//            if(!bool){
//                String openId=getOpenId(code);
//
//                TbUserVo tbUserVo = new TbUserVo();
//                tbUserVo.setOpenId(openId);
//                tbUserVo.setNickname(nickname);
//                tbUserVo.setPhoto(photo);
//                tbUserVo.setName(nickname);
//                tbUserVo.setRole("[0]");
//                tbUserVo.setHiredate(new Date());
//                tbUserVo.setStatus(1);
//                tbUserVo.setCreateTime(new Date());
//                tbUserVo.setRoot(true);
//                tbUserMapper.insert(tbUserVo);
//
//                return tbUserVo.getId();
//            }
//            else{//如果root账号被绑定了抛出异常
//                throw new TeamsException("无法绑定超级管理员账号");
//            }
//        } else{
//            //TODO普通员工注册sss
//        }
//        return 0;
//    }
        log.info("Starting user registration with registerCode: {}", registerCode);

        if (registerCode.equals("000000")) {
            try {
                boolean bool = tbUserMapper.haveRootUser();
                log.info("Root user exists: {}", bool);

                if (!bool) {
                    String openId = getOpenId(code);
                    log.info("Received OpenID: {}", openId);

                    TbUserVo tbUserVo = new TbUserVo();
                    tbUserVo.setOpenId(openId);
                    tbUserVo.setNickname(nickname);
                    tbUserVo.setPhoto(photo);
                    tbUserVo.setName(nickname);
                    tbUserVo.setRole("[0]");
                    tbUserVo.setHiredate(new Date());
                    tbUserVo.setStatus(1);
                    tbUserVo.setCreateTime(new Date());
                    tbUserVo.setRoot(true);
                    tbUserMapper.insertInt(tbUserVo);


                    MessageEntity entity = new MessageEntity();
                    entity.setSenderId(0);//系统发送设为0
                    entity.setSenderName("系统消息");
                    entity.setUuid(IdUtil.simpleUUID());
                    entity.setMsg("欢迎您注册成为超级管理员,请及时更新你的员工个人信息");
                    entity.setSendTime(new Date());
                    messageTask.send(tbUserVo.getId()+"",entity);



                    log.info("Super admin user registered successfully with ID: {}", tbUserVo.getId());
                    return tbUserVo.getId();
                } else {
                    log.error("Failed to bind super admin account: root user already exists");
                    throw new TeamsException("无法绑定超级管理员账号");
                }
            } catch (RuntimeException e) {
                log.error("Runtime Exception during user registration", e);
                throw e;
            } catch (Exception e) {
                log.error("An unexpected error occurred during user registration", e);
                throw new TeamsException("用户注册失败", e);
            }
        } else {
            // TODO: Handle normal employee registration
        }
        return 0;
    }

    @Override
    public Set<String> searchUserPermissions(int userId) {
        return tbUserMapper.searchUserPermissions(userId);
    }

    @Override
    public Integer login(String code) {
        String openId = getOpenId(code);
        Integer id = tbUserMapper.searchIdByOpenId(openId);
        if(id==null){
            throw new TeamsException("账户不存在");
        }
        //TODO 从消息队列中接收消息,转移到消息表
        messageTask.receiveAsync(id+"");
        return id;
    }

    @Override
    public TbUser searchById(int userId) {
        return tbUserMapper.searchById(userId);
    }

    @Override
    public String searchUserHiredate(int userId) {
        return tbUserMapper.searchUserHiredate(userId);
    }

    @Override
    public HashMap searchUserSummary(int userId) {
        return tbUserMapper.searchUserSummary(userId);
    }


    @Autowired
    private TbDeptMapper tbDeptMapper;

    @Override
    public ArrayList<HashMap> searchUserGroupByDept(String keyword) {
        ArrayList<HashMap> list_1=tbDeptMapper.searchDeptMembers(keyword);
        ArrayList<HashMap> list_2=tbUserMapper.searchUserGroupByDept(keyword);
        //为部门添加员工
        for(HashMap map_1:list_1){
            long deptId=(Long)map_1.get("id");
            ArrayList members=new ArrayList();
            for(HashMap map_2:list_2){
                long id=(Long) map_2.get("deptId");
                if(deptId==id){
                    members.add(map_2);
                }
            }
            map_1.put("members",members);
        }
        return list_1;
    }

    @Override
    public ArrayList<HashMap> searchMembers(List param) {
        return tbUserMapper.searchMembers(param);
    }


    @Override
    public HashMap SearchUserinfomation(int userId) {
        return tbUserMapper.searchUserSummary(userId);
    }



    @Override
    public TbUser getUserById(Integer id) {
        return tbUserMapper.getUserById(id);
    }

    @Override
    public ArrayList<HashMap> searchcontacts(HashMap map) {
        return tbUserMapper.searchcontacts(map);
    }

    @Override
    public ArrayList<HashMap> addtel(HashMap map) {
        ArrayList<HashMap> list_1=tbUserMapper.addtel(map);

        return list_1;
    }

    @Override
    public void insert(Contacts contacts) {
        tbUserMapper.insert(contacts);
    }



//    @Override
//    public List<TbUser> getAllUsers(){
//        return TbUserMapper.
//    }

}